﻿using System;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace Beeflys
{
    sealed class Mailbox : IDisposable
    {
        public Mailbox()
        {
            var opt = new UnboundedChannelOptions()
            {
                SingleReader = true
            };
            this.channel = Channel.CreateUnbounded<ActorContext>(opt);
        }
        
        private Channel<ActorContext> channel;
        
        public int Readable
        {
            get { return this.channel.Reader.Count; }
        }

        public ValueTask WriteAsync(ActorContext context, CancellationToken token = default)
        {
            return this.channel.Writer.WriteAsync(context, token);
        }

        public ValueTask<ActorContext> ReadAsync(CancellationToken token = default)
        {
            return this.channel.Reader.ReadAsync(token);
        }

        public void Dispose()
        {
            this.channel.Writer.TryComplete();
        }
    }
}